package gappengko;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

 /** Various operations to transform a HttpServletRequest object into operations
  * for SimpleDatastore
 */
public class HttpRequestHandler {

	private final JsonSimpleDatastore _sds = new JsonSimpleDatastore(System.getProperty("gappengko.kind"));

	/** returns the json representation of the entity with key equals 
	 * to the parameter GET/POST _key 
	 */
  public String getJson(HttpServletRequest req) throws Exception {
    return _sds.getJSON(req.getParameter(Constants.KEY)).toString();    
  }
	
  /** Transforms the raw request.getParameterMap() into a usable Map<String,String> */
  private Map<String,String> getMap(HttpServletRequest request) {
    Map parameters = request.getParameterMap();
    Map<String,String> result = new HashMap<String, String>();
    for(Object key: parameters.keySet()) {
      String[] value = (String[]) parameters.get(key); 
      result.put(key.toString(), value[0]);
    }
    
    result.remove(Constants.CALLBACK);
    result.remove("_");
    result.remove(RecaptchaUtils.RECAPTCHA_CHALLENGE_FIELD);
    result.remove(RecaptchaUtils.RECAPTCHA_RESPONSE_FIELD);
    result.remove("_");
    
    return result;
    
  }  
  
  /** Creates a new entity based on the information present in the request */
	public String createEntityFromRequest(HttpServletRequest req) throws Exception {
		Map<String, String> m = getMap(req);
		return _sds.createEntity(m).get(Constants.KEY).getAsString();
	}
	

	/** Gets a list of JSONObject bas on the parameters in the request */
	public JsonArray search(HttpServletRequest req) throws Exception {
    Map<String, String> m = getMap(req);
		return _sds.search(m);
	}

	
	 /** Gets a list of lists of JSONObject based on the parameters in the request */
  public JsonArray multipleSearch(HttpServletRequest req) throws Exception {
    JsonArray result = new JsonArray();
    
    // getting the post data
    BufferedReader reader = req.getReader();
    StringBuilder sb = new StringBuilder();
    String line = reader.readLine();
    while (line != null) {
        sb.append(line + "\n");
        line = reader.readLine();
    }
    reader.close();
    String postData = sb.toString();
    // the post data should be in JSON
    JsonArray array = new JsonParser().parse(postData).getAsJsonArray();
    
    // for each object in the list
    for (JsonElement elem : array) {
      result.add(_sds.search(elem.getAsJsonObject()));
    }
    
    return result;
  }

}
